import { World } from '@ecs/index'
import { getWorldData } from './tool'
import { Image, Position, Render, Size, Velocity } from '../components'

/**
 * 创建背景
 * @param world 世界实例
 * @returns 无
 */
export function createBackground(world: World): void {
  const { canvas, sprites, spritesData } = getWorldData(world)
  world.addEntityWithComponents(
    world.createEntity('background'),
    new Image(sprites, [
      {
        sx: spritesData.background.sx,
        sy: spritesData.background.sy,
        sw: spritesData.background.sw,
        sh: spritesData.background.sh
      }
    ]),
    new Position(0, 0),
    new Size(canvas.width, canvas.height),
    new Render('image')
  )
}

/**
 * 创建地板
 * @param world 世界实例
 * @returns 无
 */
export function createFloor(world: World): void {
  const { canvas, speed, sprites, spritesData } = getWorldData(world)
  world.addEntityWithComponents(
    world.createEntity('floor'),
    new Image(sprites, [
      {
        sx: spritesData.floor.sx,
        sy: spritesData.floor.sy,
        sw: spritesData.floor.sw,
        sh: spritesData.floor.sh
      }
    ]),
    new Position(0, canvas.height - spritesData.floor.sh),
    new Size(canvas.width * 2, spritesData.floor.sh),
    new Velocity(-speed),
    new Render('image', 1)
  )
}

/**
 * 创建障碍物
 * @param world 世界实例
 * @returns 无
 */
export function createObstacles(world: World): void {
  const { canvas, speed, gap, sprites, spritesData } = getWorldData(world)
  const minTop = canvas.height / 4.8 // 上障碍物最低高度
  const maxTop = canvas.height / 2 // 上障碍物最高高度
  const top = minTop + Math.random() * (maxTop - minTop) // 上障碍物随机高度
  const dh = canvas.height / 2
  // 1.上障碍物
  world.addEntityWithComponents(
    world.createEntity('upObstacle'),
    new Image(sprites, [
      {
        sx: spritesData.upObstacle.sx,
        sy: spritesData.upObstacle.sy,
        sw: spritesData.upObstacle.sw,
        sh: spritesData.upObstacle.sh
      }
    ]),
    new Position(canvas.width, top - dh),
    new Size(spritesData.upObstacle.sw * (dh / spritesData.upObstacle.sh), dh),
    new Velocity(-speed),
    new Render('image')
  )
  // 2.下障碍物
  world.addEntityWithComponents(
    world.createEntity('downObstacle'),
    new Image(sprites, [
      {
        sx: spritesData.downObstacle.sx,
        sy: spritesData.downObstacle.sy,
        sw: spritesData.downObstacle.sw,
        sh: spritesData.downObstacle.sh
      }
    ]),
    new Position(canvas.width, top + gap),
    new Size(
      spritesData.downObstacle.sw * (dh / spritesData.downObstacle.sh),
      dh
    ),
    new Velocity(-speed),
    new Render('image')
  )
}
